<template>
    <div class="recommended-question-form-container">
        <!-- 页面头部 -->
        <div class="page-header">
            <div class="header-content">
                <div class="header-left">
                    <h2>{{ isEdit ? '编辑问题' : '新增问题' }}</h2>
                </div>
                <div class="header-right">
                    <el-button @click="handleCancel">
                        <el-icon>
                            <ArrowLeft />
                        </el-icon>
                        返回
                    </el-button>
                </div>
            </div>
        </div>

        <!-- 表单内容 -->
        <div class="form-content">
            <el-card shadow="never" class="form-card">
                <el-form ref="questionFormRef" :model="formData" :rules="formRules" label-width="120px"
                    class="recommended-question-form">
                    <el-row :gutter="20">
                        <!-- 语言 -->
                        <el-col :span="12">
                            <el-form-item label="语言:" prop="language">
                                <el-select v-model="formData.language" placeholder="请选择语言" style="width: 100%">
                                    <el-option label="中文" value="zh-CN" />
                                    <el-option label="英文" value="en-US" />
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <!-- 排序顺序 -->
                        <el-col :span="12">
                            <el-form-item label="排序顺序:">
                                <el-input-number v-model="formData.sortOrder" :min="0" :max="999999"
                                    placeholder="输入排序顺序" style="width: 100%" />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <!-- 问题内容 -->
                    <el-form-item label="问题内容:" prop="questionContent">
                        <el-input v-model="formData.questionContent" type="textarea" :rows="6" placeholder="输入问题内容"
                            maxlength="500" show-word-limit />
                    </el-form-item>

                    <!-- 设置人数 -->
                    <el-form-item label="设置人数:" prop="setCount">
                        <el-input-number v-model="formData.setCount" :min="0" :max="999999"
                            placeholder="输入设置人数" style="width: 300px" />
                    </el-form-item>

                    <!-- 操作按钮 -->
                    <el-form-item>
                        <div class="form-actions">
                            <el-button @click="handleCancel">取消</el-button>
                            <el-button type="primary" @click="handleSubmit" :loading="loading">保存</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowLeft } from '@element-plus/icons-vue';
import { RecommendedQuestionFormData, RecommendedQuestionEditData } from '@/types/recommendedQuestion';
import { createRecommendedQuestion, updateRecommendedQuestion, getRecommendedQuestionById } from '@/api/system/recommendedQuestion';

const route = useRoute();
const router = useRouter();

const id = route.params.id as string;
const isEdit = computed(() => !!id);

// 表单引用
const questionFormRef = ref();
const loading = ref(false);

// 表单数据
const formData = reactive<RecommendedQuestionFormData>({
    questionContent: '',
    setCount: 0,
    sortOrder: 0,
    language: 'zh-CN'
});

// 表单验证规则
const formRules = {
    questionContent: [
        { required: true, message: '请输入问题内容', trigger: 'blur' },
        { min: 2, max: 500, message: '问题内容长度2-500个字符', trigger: 'blur' }
    ],
    setCount: [
        { required: true, message: '请输入设置人数', trigger: 'blur' },
        { type: 'number', min: 0, message: '设置人数必须大于等于0', trigger: 'blur' }
    ],
    language: [
        { required: true, message: '请选择语言', trigger: 'change' }
    ],
    sortOrder: [
        { required: true, message: '请输入排序顺序', trigger: 'blur' },
        { type: 'number', min: 0, message: '排序顺序必须大于等于0', trigger: 'blur' }
    ]
};

// 提交表单
const handleSubmit = async () => {
    if (!questionFormRef.value) return;

    try {
        await questionFormRef.value.validate();

        await ElMessageBox.confirm(
            `确定要${isEdit.value ? '更新' : '保存'}此问题吗？`,
            '确认操作',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'success',
            }
        );

        loading.value = true;

        // 准备提交数据
        const submitData = { ...formData };

        let res;
        if (isEdit.value) {
            // 编辑模式
            res = await updateRecommendedQuestion({ id, ...submitData });
        } else {
            // 新增模式
            res = await createRecommendedQuestion(submitData);
        }

        const responseData = res as any;
        if (responseData && responseData.code === 200) {
            ElMessage.success(`${isEdit.value ? '更新' : '保存'}成功`);
            router.push('/recommended-question-list');
        } else {
            const errorMsg = (responseData && responseData.msg) || `${isEdit.value ? '更新' : '保存'}失败`;
            ElMessage.error(errorMsg);
        }

    } catch (error) {
        if (error !== 'cancel') {
            console.error('保存推荐问题失败:', error);
            ElMessage.error('操作失败，请稍后重试');
        }
    } finally {
        loading.value = false;
    }
};

// 取消操作
const handleCancel = () => {
    router.push('/recommended-question-list');
};

// 加载问题数据
const loadQuestionData = async (questionId: string) => {
    try {
        loading.value = true;
        const res = await getRecommendedQuestionById(questionId);
        const responseData = res as any;

        if (responseData && responseData.code === 200 && responseData.data) {
            const questionData = responseData.data;

            // 填充表单数据
            Object.assign(formData, {
                questionContent: questionData.questionContent || '',
                setCount: questionData.setCount || 0,
                sortOrder: questionData.sortOrder || 0,
                language: questionData.language || 'zh-CN'
            });
        } else {
            const errorMsg = (responseData && responseData.msg) || '获取推荐问题详情失败';
            ElMessage.error(errorMsg);
        }
    } catch (error) {
        console.error('获取推荐问题详情失败:', error);
        ElMessage.error('获取推荐问题详情失败，请稍后重试');
    } finally {
        loading.value = false;
    }
};

// 页面初始化
onMounted(() => {
    if (isEdit.value) {
        // 编辑模式：加载现有数据
        loadQuestionData(id);
    }
});
</script>

<style scoped>
.recommended-question-form-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

.page-header {
    border-radius: 8px;
    margin-bottom: 20px;
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left h2 {
    margin: 0;
    color: #333;
    font-size: 24px;
}

.form-content {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.form-card {
    border-radius: 8px;
}

.recommended-question-form {
    padding: 30px;
}

.form-hint {
    color: #f56c6c;
    font-size: 12px;
    margin-top: 4px;
}

.form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .recommended-question-form-container {
        padding: 10px;
    }

    .header-content {
        flex-direction: column;
        gap: 16px;
        align-items: flex-start;
    }

    .recommended-question-form {
        padding: 20px;
    }

    .form-actions {
        justify-content: center;
    }
}
</style>
